package mvapp;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;

import javax.swing.*;

public class DataAPPMainFrame extends JFrame {
	private DataModel d_model = new DataModel();
	private final int COLUMN = 9;

	//设置一一对应的标题
	private final List<String> TITLES = Arrays.asList("Time","First", "Second", "Third", "Fourth", "fifth", "sixth","seventh","Eighth");
	private final List<String> VTITLES = Arrays.asList("时间/星期","第一节课", "第二节课", "第三节课", "第四节课", "第五节课", "第六节课", "第七节课", "第八节课");

	private Vector<Vector<String>> dataModel = new Vector<Vector<String>>();

	//设置查询主题，即各个位置的框的作用
	private QueryItem week = new QueryItem("星期：", 5);
	private QueryItem2 weeks = new QueryItem2("星期自：", "到", 5);
	private QueryItem time = new QueryItem("需要插入的星期是：",5);


	//设置四个按钮
	private JButton queryBtn = new JButton("查询");
	private JButton saveBtn = new JButton("修改");
	private JButton insertBtn = new JButton("插入");
	private JButton deleteBtn = new JButton("删除");


	/*
	* 设置填写需要添加的课程的编辑框
	* */
	private QueryItem Fir = new QueryItem("First",3);
	private QueryItem Sec = new QueryItem("Second",3);
	private QueryItem Thi = new QueryItem("Third",3);
	private QueryItem Fou = new QueryItem("Fourth",3);
	private QueryItem Fif = new QueryItem("Fifth",3);
	private QueryItem Six = new QueryItem("Sixth",3);
	private QueryItem Sev = new QueryItem("Seventh",3);
	private QueryItem Eig = new QueryItem("Eighth",3);

	private QueryItem Date = new QueryItem("修改的数据：",3);

	//文本框
	private JTextArea textarea = new JTextArea(5, 5);

	private MyTable table;

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		//构造一个frame窗口,标题为括号里面的字符串
		DataAPPMainFrame frame = new DataAPPMainFrame("课程表信息录入和查询");

		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		frame.setMinimumSize(new Dimension(1000, 500));
		//是否可以被看见
		frame.setVisible(true);
		//是否可以被调整大小
		frame.setResizable(false);
	}

	// 构造函数，负责创建用户界面
	public DataAPPMainFrame(String title) throws SQLException, ClassNotFoundException {
		super(title);

		Vector<String> titles = new Vector<String>(VTITLES);
		table = new MyTable(dataModel, titles);

//设置对应列的宽度。从0开始计数
		table.getColumnModel().getColumn(0).setPreferredWidth(150);

		JPanel controlPanel = new JPanel();

		JPanel FirstPanel = new JPanel();
		JPanel SecondPanel = new JPanel();
		JPanel ThirdPanel = new JPanel();

		//设置一个主面板，为表格布局
		controlPanel.setLayout(new BorderLayout());

		//设置两个嵌入主面板的副面板，为流式布局
		FirstPanel.setLayout(new FlowLayout());
		SecondPanel.setLayout(new FlowLayout());
		ThirdPanel.setLayout(new FlowLayout());

		//向第一个副面板里面添加组件
		FirstPanel.add(week);
		FirstPanel.add(weeks);
		FirstPanel.add(time);
		FirstPanel.add(Date);

		//向第二个副面板中添加组件
		SecondPanel.add(queryBtn);
		SecondPanel.add(saveBtn);
		SecondPanel.add(insertBtn);
		SecondPanel.add(deleteBtn);

		//向第三个副面板里面添加组件，用来记录需要添加的课程
		ThirdPanel.add(Fir);
		ThirdPanel.add(Sec);
		ThirdPanel.add(Thi);
		ThirdPanel.add(Fou);
		ThirdPanel.add(Fif);
		ThirdPanel.add(Six);
		ThirdPanel.add(Sev);
		ThirdPanel.add(Eig);

		//将两个副面板添加进主面板
		controlPanel.add(FirstPanel,BorderLayout.NORTH);
		controlPanel.add(SecondPanel,BorderLayout.CENTER);
		controlPanel.add(ThirdPanel,BorderLayout.SOUTH);

		//设置控件大小，为最佳的显示大小，可以随着控件变化
		controlPanel.setPreferredSize(new Dimension(0, 130));

		JPanel tablePanel = new JPanel();
		//创建一个箱式布局，方向是从上到下垂直排列
		tablePanel.setLayout(new BoxLayout(tablePanel, BoxLayout.Y_AXIS));
		tablePanel.add(Box.createRigidArea(new Dimension(0, 20)));
		tablePanel.add(table.getTableHeader());

		//滑动条
		tablePanel.add(new JScrollPane(table));

		JPanel container = new JPanel();
		container.setLayout(new BorderLayout());
		container.add(textarea, BorderLayout.NORTH);
		container.add(tablePanel, BorderLayout.CENTER);

		this.add(controlPanel, BorderLayout.NORTH);
		this.add(container, BorderLayout.CENTER);
		this.add(Box.createRigidArea(new Dimension(20, 0)), BorderLayout.WEST);
		this.add(Box.createRigidArea(new Dimension(20, 0)), BorderLayout.EAST);
		this.add(Box.createRigidArea(new Dimension(0, 20)), BorderLayout.SOUTH);

		setActionListener();
	}

	// 程序启动时，需调用该方法连接到数据库
	// 之所以不放在构造函数中，是因为这些操作可能抛出异常，需要单独处理

	private void setActionListener() {
		// 根据指定条件，列出数据库中满足条件的记录
		queryBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				ArrayList<String> conditions = new ArrayList<String>();
				if (week.isSelected())
					conditions.add("(Time = '" + week.getText() + "')");

				if (weeks.isSelected())
					conditions.add("(Time >= " + weeks.getText() + " AND " + "Time <= " + weeks.getText2() + ")");

				
				String queryString = d_model.buildSQLQuery(conditions);
				textarea.setText(queryString);

				dataModel.clear();
  //             Statement stmt;

				try {
					dataModel.addAll(d_model.getQueryResult(queryString));
				} catch (Exception e1) {
					e1.printStackTrace();
				}
//                dataModel.add
				// 更新表格
				table.validate();
				table.updateUI();
			}

		});

		// 根据用户当前选中的单元格，修改数据库中对应记录的对应字段
		saveBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				int row = table.getSelectedRow();
				int column = table.getSelectedColumn();
				if (row == -1 || column == 0)
					return;

				String val = dataModel.get(row).get(column);
				String dat = Date.getText();
				val = dat;
				String Time = dataModel.get(row).get(0);
				String cmd = d_model.buildSQLUpdateStatement(column, val, Time);
				textarea.setText(cmd);

//				PreparedStatement ps;
				try {
					int rs = d_model.exeSQLStatement(cmd);
				} catch (Exception e1) {
					e1.printStackTrace();
				}

			}
		});

		// 往数据库中插入一条新的记录
		insertBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				String Time = week.getText();
				String Times = weeks.getText();
				String insert = time.getText();

				String a = Fir.getText();
				String b = Sec.getText();
				String c = Thi.getText();
				String d = Fou.getText();
				String e2 = Fif.getText();
				String f = Six.getText();
				String g = Sev.getText();
				String h = Eig.getText();



				// 在文本框显示 SQL 命令
				String cmd =d_model.buildSQLInsertStatement(insert,a,b,c,d,e2,f,g,h);
				textarea.setText(cmd);

//				PreparedStatement ps;
				try {
					int rs=d_model.exeSQLStatement(cmd);
					dataModel.add(new Vector<String>(Arrays.asList(Time, Times)));

					// 更新表格
					table.validate();
					table.updateUI();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}
		});

		// 将用户当前选中的记录从数据库中删除
		deleteBtn.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				int row = table.getSelectedRow();
				String Time = dataModel.get(row).get(0);
				String sql = d_model.buildSQLDeleteStatement(Time);

				// 在文本框显示 SQL 命令
				textarea.setText(sql);

//				Statement stmt;
				try {
					int rs = d_model.exeSQLStatement(sql);
					dataModel.remove(row);

					// 更新表格
					table.validate();
					table.updateUI();
				} catch (Exception e1) {
					e1.printStackTrace();
				}
			}

		});
	}

}

/*
 * 查询项目 将复选框、标签、文本框组合成一个组件 对外提供获取文本和选中状态的两个方法
 */
class QueryItem extends JPanel {
	private JCheckBox checkbox;
	private JLabel label;
	private JTextField textfield;

	public QueryItem(String labelText, int textWidth) {
		checkbox = new JCheckBox();
		label = new JLabel(labelText);
		textfield = new JTextField(textWidth);
		this.add(checkbox);
		this.add(label);
		this.add(textfield);
	}

	public boolean isSelected() {
		return checkbox.isSelected();
	}

	public String getText() {
		return textfield.getText();
	}
}

/*
 * 同样是查询项目 这是用于查询日期范围的组件，包含了两个文本框
 * 因此特殊处理，并增加了获取第二个文本框内容的方法
 */
class QueryItem2 extends QueryItem {
	private JLabel label2;
	private JTextField textfield2;

	public QueryItem2(String labelText, String labelText2, int textWidth) {
		super(labelText, textWidth);
		label2 = new JLabel(labelText2);
		textfield2 = new JTextField(textWidth);
		this.add(label2);
		this.add(textfield2);
	}

	public String getText2() {
		return textfield2.getText();
	}
}

/*
 * 表格组件
 */
class MyTable extends JTable {

	public MyTable(Vector data, Vector title) {
		super(data, title);
	}

/**		重载了 JTable 的 isCellEditable 方法 目的是防止编辑 Time 字段，禁止修改主键
*	第一列不可以编辑，其他可以
*	@Override
*	public boolean isCellEditable(int row, int column) {
*		if (column == 0 )
*			return false;
*		else
*			return true;
*	}
**/

}